package cn.leida.ruoyi.client.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.leida.ruoyi.client.service.ICleanSysDataService;
import cn.leida.ruoyi.common.core.domain.entity.SysUser;
import cn.leida.ruoyi.common.utils.DateUtils;
import cn.leida.ruoyi.common.utils.SecurityUtils;
import cn.leida.ruoyi.system.dao.SysLoginInforDao;
import cn.leida.ruoyi.system.dao.SysOperLogDao;
import cn.leida.ruoyi.system.dao.SysUserDao;
import cn.leida.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 清理sys数据
 *
 * @author liutietou
 * @since 1.0  2020-12-11
 */
@Service
public class CleanSysDataServiceImpl implements ICleanSysDataService {

    @Autowired
    private SysLoginInforDao loginInforDao;

    @Autowired
    private SysOperLogDao logDao;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysUserDao userDao;

    /**
     * 清理客户端数据
     *
     * @param deleteDays 删除X天之前数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cleanClientSysData(int deleteDays) {
        try {
            deleteSysData(deleteDays);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化超级管理员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initAdminUser() {
        String admin = StrUtil.trim("admin");
        String realPassword = StrUtil.trim("admin123");
        List<SysUser> userList = userDao.findUserList(admin);
        if (CollectionUtil.isEmpty(userList)) {
            SysUser user = new SysUser();
            user.setUserName(admin);
            user.setCreateBy(admin);
            user.setNickName("雷达数据");
            user.setEmail("leida@163.com");
            user.setPhoneNumber("18888888888");
            user.initCreateTime();
            user.setStatus("0");
            user.setDelFlag("0");
            user.setPassword(SecurityUtils.encryptPassword(realPassword));
            user.setRemark("超级管理员");
            userDao.save(user);
        }
    }

    /**
     * 删除sys数据
     */
    @Transactional(rollbackFor = Exception.class)
    private void deleteSysData(int deleteDays) {
        // x天前
        String dateTime = DateUtils.dateTime(deleteDays);
        try {
            // 删除登录日志
            loginInforDao.deleteSysLoginInfor(dateTime);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        try {
            // 删除操作日志
            logDao.deleteSysOperLog(dateTime);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}
